package com.tplan.tplanrabbitmqserver.receive;

import com.tplan.constants.EmailConstants;
import com.tplan.domain.Email;
import com.tplan.tplanrabbitmqserver.config.MQConfig;
import com.tplan.util.PojoUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailMqReceive {
    @Autowired
    private Environment env;

    @Autowired
    private JavaMailSender javaMailSender;

    @RabbitListener(queues = MQConfig.USER_EMAIL_QUEUE)
    public void receiveEmail(String message) {
        SimpleMailMessage msg = new SimpleMailMessage();
        Email email = PojoUtil.stringToBean(message, Email.class);
        msg.setFrom(env.getProperty(EmailConstants.EMAIL_FROM));
        msg.setTo(email.getTarget());
        msg.setSubject(email.getTitle());
        msg.setText(email.getContent());

        javaMailSender.send(msg);
    }
}
